<?php
/**
 * Created by 七月.
 * Author: 七月
 * 微信公号：小楼昨夜又秋风
 * 知乎ID: 七月在夏天
 * Date: 2017/2/19
 * Time: 2:42
 */

namespace app\api\model;


use think\Model;
use traits\model\SoftDelete;

class BaseModel extends Model
{
    // 软删除，设置后在查询时要特别注意whereOr
    // 使用whereOr会将设置了软删除的记录也查询出来
    // 可以对比下SQL语句，看看whereOr的SQL
    use SoftDelete;
    
    protected $hidden = ['delete_time'];
    
    protected function  prefixImgUrl($value, $data){
        $finalUrl = $value;
        if(substr($value,0,4) === 'http'){
            return $finalUrl;
        }
        if($data['from'] == 1){
            $finalUrl = config('setting.img_prefix').$value;
        }elseif($data['from'] == 3){
            $finalUrl = config('setting.medisum_img_prefix').$value;
        }
        return $finalUrl;
    }
    //    重命名并存储文件，返回新的文件名数组
    protected static function saveFiles($values,$set_path){
        $name_urls = array();
        foreach($values as $key => $value){
            $file_name = $value['name'];
            $exe_name  = self::getExeName($file_name);
            $data_path = date('Ymd');
            $new_file_name = uniqid().getRandChars(19).'.'.$exe_name;
            $end_path_name = $data_path.'/'.$new_file_name;
            // 判断是否为视频格式，以便获取视频第一帧图片作为封面图
            $ext_ary = config('setting.video_ext_ary');
            if(in_array($exe_name,$ext_ary)){
                $video_name = $new_file_name;
                // 生成视频对应的图片名
                $video_name_ary = explode('.',$video_name);
                array_pop($video_name_ary);
                $video_img_name = implode('.',$video_name_ary).'.jpg';
                $video_img_path_name = $data_path.'/'.$video_img_name;
                // 是视频格式，将视频和视频图片保存到一个数组中
                $name_urls[$key]['video'] = $end_path_name;
                $name_urls[$key]['img'] = $video_img_path_name;
            }else{
                $name_urls[$key] = $end_path_name;
            }
            // 图片文件夹+日期的目录绝对路径
            $absolute_path = $set_path.$data_path;
            if($value['tmp_name']){
                if(!is_dir($absolute_path)){
                    mkdir($absolute_path,0777,true);
                }
                move_uploaded_file($value['tmp_name'],$set_path.$end_path_name);
                // 保存视频第一帧图片
                if(in_array($exe_name,$ext_ary)) {
                    $img_path = $set_path . $video_img_path_name;
                    $str = "ffmpeg -i " . $set_path.$end_path_name . " -y -f mjpeg -ss 0 -t 1 -s 740x500 " . $img_path;
                    exec($str);
                }
            }
        }
        return $name_urls;
    }
    //获取文件扩展名（后缀）
    protected static function getExeName($fileName){
        $pathinfo = pathinfo($fileName);
        return strtolower($pathinfo['extension']);
    }
    
}